var express = require("express");
var app = express();
var bodyParser = require("body-parser");
app.use(
  bodyParser.urlencoded({
    extended: true
  })
);
app.use(bodyParser.json());
var url = require("url");

//引入User处理
const { UserControl } = require("./beans/User");
const { ChatControl } = require("./beans/Chat");

//注册User
let ControllerReigistry = {
  user: UserControl,
  chat:ChatControl,
};

/*----------------中文处理------------*/
function urlEncodeChinese(req, res, next) {
  var decodeurlchinese = url.parse(req.url);
  var tmpdecodepath = decodeurlchinese.pathname;
  decodeurlchinese.pathname = decodeURIComponent(decodeurlchinese.pathname);
  decodeurlchinese.path = decodeurlchinese.path.replace(
    tmpdecodepath,
    decodeurlchinese.pathname
  ); // 不需要正则全局替换，这样有可能把参数也给替换了
  req.url = req.originalUrl = decodeurlchinese.path;
  next();
}
app.use(urlEncodeChinese);
/*------------------end-------------- */

/**
 * req（request）是前端发来的数据
 * res（response）是一个响应对象，它可以用来向前端返回数据
 * 
 * /chat/add
 */
app.post("/:server/:method", (req, res) => {
  let server = req.params.server;
  let method = req.params.method;
  //如果前端请求的是/user/get，那么server=='user'，method=='get'

  /**
   * ControllerReigistry是一个我写的对象
   * 如果server=='user
   * 下面代码等价于获取ControllerReigistry['user']
   * 换言之，拿到的是UserControl对象
   * */
  let controller = ControllerReigistry[server.toLowerCase()];
  if (controller) {
    if (controller.status == -1) {
      controller.$start(
        () => {
          console.log(`[${server}]控制器初始化成功`);
        },
        () => {
          res.json({
            msg: `[${server}]控制器初始化失败`,
            status: -1
          });
        }
      );
    }
    let m;
    try {
      /**
       * 如果method=='get'
       * controller[method]事实上是：
       * UserControl.get
       */
      if ((m = controller[method])) {
        m.call(
          controller,
          req.body,
          //正确处理函数
          data => {
            //res返回status：1和数据
            res.json({
              status: 1,
              data: data
            });
          },
          //错误处理函数
          e => {
            // res返回status:-1和错误信息
            res.json({
              msg: e,
              status: -1
            });
          }
        );
      } else {
        res.json({
          msg: `服务[${server}]里没有改方法[${method}]`,
          status: -1
        });
      }
    } catch (e) {
      console.error(e);
      res.json({
        msg: e,
        status: -1
      });
    }
  } else {
    res.json({
      msg: `找不到服务[${server}]`,
      status: -1
    });
  }
});
app.get("/*", (req, res) => {
  console.log("代理成功", req.body);
  res.json(req.params);
});

app.post("/*", (req, res) => {
  console.log(req);
  res.json({});
});

app.listen(8881, function() {
  console.log("Server running at http://127.0.0.1:8881/");
});
